package org.jeecg.modules.demo.hdpeersupervision.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.query.QueryRuleEnum;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.MinioUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.hdpeersupervision.entity.HdPeerSupervision;
import org.jeecg.modules.demo.hdpeersupervision.entity.HdPeerSupervisionVo;
import org.jeecg.modules.demo.hdpeersupervision.service.IHdPeerSupervisionService;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.service.ISysDepartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: 同级监督（党委）
 * @Author: jeecg-boot
 * @Date: 2025-07-02
 * @Version: V1.0
 */
@Tag(name = "同级监督")
@RestController
@RequestMapping("/hdpeersupervision/hdPeerSupervision")
@Slf4j
public class HdPeerSupervisionController extends JeecgController<HdPeerSupervision, IHdPeerSupervisionService> {
    @Autowired
    private IHdPeerSupervisionService hdPeerSupervisionService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    ;


    /**
     * 分页列表查询
     *
     * @param hdPeerSupervision
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "同级监督-分页列表查询")

//	public Result<IPage<HdPeerSupervision>> queryPageList(HdPeerSupervision hdPeerSupervision,
//								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
//								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
//								   HttpServletRequest req) {
//        // 自定义查询规则
//        Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
//        // 自定义多选的查询规则为：LIKE_WITH_OR
//        customeRuleMap.put("project", QueryRuleEnum.LIKE_WITH_OR);
//        customeRuleMap.put("companyDepartment", QueryRuleEnum.LIKE_WITH_OR);
//        QueryWrapper<HdPeerSupervision> queryWrapper = QueryGenerator.initQueryWrapper(hdPeerSupervision, req.getParameterMap(),customeRuleMap);
//		Page<HdPeerSupervision> page = new Page<HdPeerSupervision>(pageNo, pageSize);
//		IPage<HdPeerSupervision> pageList = hdPeerSupervisionService.page(page, queryWrapper);
//		return Result.OK(pageList);
//	}
    @Operation(summary = "同级监督-分页列表查询", description = "同级监督-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<HdPeerSupervision>> queryPageList(HdPeerSupervision hdPeerSupervision,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        //获取登录人的信息
        LoginUser loginUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (loginUser.getRoleCode().equals("admin")||loginUser.getRoleCode().equals("leader")) {
            // 自定义查询规则
            Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
            // 自定义多选的查询规则为：LIKE_WITH_OR
            customeRuleMap.put("project", QueryRuleEnum.LIKE_WITH_OR);
            customeRuleMap.put("companyDepartment", QueryRuleEnum.LIKE_WITH_OR);
            QueryWrapper<HdPeerSupervision> queryWrapper = QueryGenerator.initQueryWrapper(hdPeerSupervision, req.getParameterMap(), customeRuleMap);
            Page<HdPeerSupervision> page = new Page<HdPeerSupervision>(pageNo, pageSize);
            IPage<HdPeerSupervision> pageList = hdPeerSupervisionService.page(page, queryWrapper);
            return Result.OK(pageList);
        } else {
            String id = loginUser.getDepartIds();
            String departName = sysDepartService.getDepartNameById(id);
            // 自定义查询规则
            Map<String, QueryRuleEnum> customeRuleMap = new HashMap<>();
            // 自定义多选的查询规则为：LIKE_WITH_OR
            customeRuleMap.put("project", QueryRuleEnum.LIKE_WITH_OR);
            QueryWrapper<HdPeerSupervision> queryWrapper = QueryGenerator.initQueryWrapper(hdPeerSupervision, req.getParameterMap(), customeRuleMap);
            queryWrapper.eq("company_department", departName);
            Page<HdPeerSupervision> page = new Page<HdPeerSupervision>(pageNo, pageSize);
            IPage<HdPeerSupervision> pageList = hdPeerSupervisionService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
    }

    /**
     * 添加
     *
     * @param hdPeerSupervision
     * @return
     */
    @AutoLog(value = "同级监督-添加")
    @Operation(summary = "同级监督-添加", description = "同级监督-添加")
    @RequiresPermissions("hdpeersupervision:hd_peer_supervision:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody HdPeerSupervision hdPeerSupervision) {
        hdPeerSupervisionService.save(hdPeerSupervision);
        return Result.OK("添加成功！");
    }

    /**
     * 添加
     *
     * @param hdPeerSupervision
     * @return
     */
    @AutoLog(value = "同级监督-添加")
    @Operation(summary = "同级监督-添加", description = "同级监督-添加")
    @RequiresPermissions("hdpeersupervision:hd_peer_supervision:add")
    @PostMapping(value = "/addBatch")
    public Result<String> addBatch(@RequestBody List<HdPeerSupervision> hdPeerSupervision) {
        hdPeerSupervisionService.saveBatch(hdPeerSupervision);
        return Result.OK("添加成功！");
    }


    /**
     * 编辑
     *
     * @param hdPeerSupervision
     * @return
     */
    @AutoLog(value = "同级监督-编辑")
    @Operation(summary = "同级监督-编辑", description = "同级监督-编辑")
    @RequiresPermissions("hdpeersupervision:hd_peer_supervision:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody HdPeerSupervision hdPeerSupervision) {
        hdPeerSupervisionService.updateById(hdPeerSupervision);
        return Result.OK("编辑成功!");
    }


    /**
     * 编辑
     *
     * @param hdPeerSupervision
     * @return
     */
    @AutoLog(value = "同级监督-编辑")
    @Operation(summary = "同级监督-编辑", description = "同级监督-编辑")
    @RequiresPermissions("hdpeersupervision:hd_peer_supervision:update")
    @RequestMapping(value = "/update", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> update(@RequestBody HdPeerSupervision hdPeerSupervision) {
        hdPeerSupervisionService.updateById(hdPeerSupervision);
        return Result.OK("编辑成功!");
    }

    /**
     * 编辑
     *
     * @param hdPeerSupervision
     * @return
     */
    @AutoLog(value = "同级监督-审核")
    @Operation(summary = "同级监督-审核", description = "同级监督-审核")
    @RequiresPermissions("hdpeersupervision:hd_peer_supervision:audit")
    @RequestMapping(value = "/audit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> audit(@RequestBody HdPeerSupervision hdPeerSupervision) {
        if (hdPeerSupervision.getFlag().equals("2")) {
            String userName = sysBaseAPI.getUserByName(hdPeerSupervision.getUpdateBy()).getUsername();
            MessageDTO message = new MessageDTO("系统", userName,
                    "信息填写错误，请修改",
                    hdPeerSupervision.getOpinion());
            sysBaseAPI.sendSysAnnouncement(message);
        }
        hdPeerSupervisionService.updateById(hdPeerSupervision);
        return Result.OK("审核完成!");
    }

    /**
     * 编辑
     *
     * @param hdPeerSupervision
     * @return
     */
    @AutoLog(value = "同级监督-重新上传")
    @Operation(summary = "同级监督-重新上传", description = "同级监督-重新上传")
    @RequiresPermissions("hdpeersupervision:hd_peer_supervision:reUpload")
    @RequestMapping(value = "/reUpload", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> reUpload(@RequestBody HdPeerSupervision hdPeerSupervision) {
        hdPeerSupervisionService.updateById(hdPeerSupervision);
        return Result.OK("重新上传!");
    }


    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "同级监督-通过id删除")
    @Operation(summary = "同级监督-通过id删除", description = "同级监督-通过id删除")
    @RequiresPermissions("hdpeersupervision:hd_peer_supervision:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        hdPeerSupervisionService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "同级监督-批量删除")
    @Operation(summary = "同级监督-批量删除", description = "同级监督-批量删除")
    @RequiresPermissions("hdpeersupervision:hd_peer_supervision:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hdPeerSupervisionService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "同级监督-通过id查询")
    @Operation(summary = "同级监督-通过id查询", description = "同级监督-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<HdPeerSupervision> queryById(@RequestParam(name = "id", required = true) String id) {
        HdPeerSupervision hdPeerSupervision = hdPeerSupervisionService.getById(id);
        if (hdPeerSupervision == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(hdPeerSupervision);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hdPeerSupervision
     */
    @RequiresPermissions("hdpeersupervision:hd_peer_supervision:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HdPeerSupervision hdPeerSupervision) {
        return super.exportXls(request, hdPeerSupervision, HdPeerSupervision.class, "同级监督");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("hdpeersupervision:hd_peer_supervision:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HdPeerSupervision.class);
    }

    @Operation(summary = "同级监督(党委)-导出excel合并单元格", description = "同级监督(党委)-导出excel合并单元格")
    @GetMapping(value = "/exportXlsMergeCells")
    public Result<byte[]> exportXlsMergeCells(HttpServletRequest request, HdPeerSupervision hdPeerSupervision) throws IOException {
        // Step.1 组装查询条件
        QueryWrapper<HdPeerSupervision> queryWrapper = new QueryWrapper<>(hdPeerSupervision);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        String department = request.getParameter("department");
//		 System.out.println("selections = " + selections);
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            System.out.println("selectionList = " + selectionList);
            queryWrapper.in("id", selectionList);
        } else if (oConvertUtils.isNotEmpty(department)){
            List<String> departmentList = Arrays.asList(department.split(","));
            queryWrapper.in("company_department", departmentList);
        }
        // Step.2 获取导出数据
        List<HdPeerSupervision> exportList = hdPeerSupervisionService.list(queryWrapper);
        // 2. 生成Excel字节数组
        byte[] excelBytes = hdPeerSupervisionService.generateExcelBytes(exportList);
        return Result.OK(excelBytes);
    }


    @Operation(summary = "同级监督(党委)-导出excel存到minio中", description = "同级监督(党委)-导出excel存到minio中")
    @GetMapping(value = "/exportXlsMergeCells1")
    public Result<String> exportXlsMergeCells1(HttpServletRequest request, HdPeerSupervision hdPeerSupervision) throws Exception {
        // Step.1 组装查询条件
        QueryWrapper<HdPeerSupervision> queryWrapper = new QueryWrapper<>();
        // 过滤选中数据
        String selections = request.getParameter("selections");
//		 System.out.println("selections = " + selections);
        String department = request.getParameter("department");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            System.out.println("selectionList = " + selectionList);
            queryWrapper.in("id",selectionList);
        }  else if (oConvertUtils.isNotEmpty(department)) {
            List<String> departmentList = Arrays.asList(department.split(","));
            queryWrapper.in("company_department",departmentList);
        }
        // Step.2 获取导出数据
        List<HdPeerSupervision> exportList = hdPeerSupervisionService.list(queryWrapper);
        // 2. 生成Excel字节数组
        byte[] excelBytes = hdPeerSupervisionService.generateExcelBytes(exportList);
        String url = MinioUtil.uploadByte(excelBytes, "excel.xlsx", "", "");
        return Result.OK(url);
    }

    @Operation(summary = "同级监督(党委)-查询所有部门的填报率", description = "同级监督(党委)-查询所有部门的填报率")
    @GetMapping(value = "/queryAllDepartmentFillRate")
    public Result<Map<String, HdPeerSupervisionVo>> queryAllDepartmentFillRate(HdPeerSupervision hdPeerSupervision) {
        Map<String, HdPeerSupervisionVo> result = new HashMap<>();
        Long total = 0L;
        Long complete = 0L;
        double fillRate = 0.0;
        List<SysDepart> departList = sysDepartService.list();
        for (int i = 0; i < departList.size(); i++) {
            String departName = departList.get(i).getDepartName();
//            System.out.println("departName = " + departName);
            // 查询该部门的总记录数
            Long DepartTotal = hdPeerSupervisionService.count(new QueryWrapper<HdPeerSupervision>()
                    .eq("company_department", departName));
//            System.out.println("DepartTotal = " + DepartTotal);
            // 如果没有记录，跳过该部门
            if (DepartTotal == 0L) {
                continue;
            }
            HdPeerSupervisionVo hdPeerSupervisionVo = new HdPeerSupervisionVo();
            total = hdPeerSupervisionService.count(new QueryWrapper<HdPeerSupervision>().eq("company_department", departList.get(i).getDepartName()));
            complete = hdPeerSupervisionService.count(new QueryWrapper<HdPeerSupervision>().eq("company_department", departList.get(i).getDepartName()).in("flag", "1", "2", "3"));
            Long notTotal = hdPeerSupervisionService.count(new QueryWrapper<HdPeerSupervision>().eq("company_department", departList.get(i).getDepartName())
                    .in("flag", "0"));
            Long pendingApprovalTotal = hdPeerSupervisionService.count(new QueryWrapper<HdPeerSupervision>().eq("company_department", departList.get(i).getDepartName())
                    .in("flag", "1"));
            Long rejectTotal = hdPeerSupervisionService.count(new QueryWrapper<HdPeerSupervision>().eq("company_department", departList.get(i).getDepartName())
                    .in("flag", "2"));
            Long agreeTotal = hdPeerSupervisionService.count(new QueryWrapper<HdPeerSupervision>().eq("company_department", departList.get(i).getDepartName())
                    .in("flag", "3"));
            hdPeerSupervisionVo.setNotTotal(notTotal);
            hdPeerSupervisionVo.setPendingApprovalTotal(pendingApprovalTotal);
            hdPeerSupervisionVo.setRejectTotal(rejectTotal);
            hdPeerSupervisionVo.setAgreeTotal(agreeTotal);
            if (total != 0L) {
                fillRate = (double) complete / total;
                fillRate=new BigDecimal(fillRate).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
                hdPeerSupervisionVo.setFillRate(fillRate);
            }
            result.put(departList.get(i).getDepartName(), hdPeerSupervisionVo);
        }
        return Result.OK(result);
    }

}
